import time
from typing import Any, Dict, Optional

import jwt

from app.settings import settings

ALGORITHM = "HS256"


def create_access_token(payload: Dict[str, Any], expires_in_seconds: int = 3600) -> str:
    to_encode = payload.copy()
    now = int(time.time())
    to_encode.update({"iat": now, "exp": now + expires_in_seconds})
    token = jwt.encode(to_encode, settings.jwt_secret, algorithm=ALGORITHM)
    return token


def decode_access_token(token: str) -> Optional[Dict[str, Any]]:
    try:
        decoded = jwt.decode(token, settings.jwt_secret, algorithms=[ALGORITHM])
        return decoded
    except jwt.PyJWTError:
        return None 